package com.zhijiaoyun.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.zhijiaoyun.common.StringUtils;
import com.zhijiaoyun.dao.IBuyHistoryDao;
import com.zhijiaoyun.model.BuyHistory;
import com.zhijiaoyun.model.dto.BuyHistoryDto;
import com.zhijiaoyun.model.dto.CourseDto;
import com.zhijiaoyun.model.dto.PageData;
import com.zhijiaoyun.model.dto.PageList;
import com.zhijiaoyun.service.IBuyHistoryService;
import com.zhijiaoyun.service.ICourseService;

/**
 * @author shisfish
 * @date 2017/6/6
 */
@Service(value = "buyHistoryService")
public class BuyHistoryServiceImpl implements IBuyHistoryService {

	@Resource
	IBuyHistoryDao buyHistoryDao;

	@Resource
	ICourseService courseService;
	
	@Override
	public void addBuyService(BuyHistory buyHistory) {
		buyHistoryDao.insert(buyHistory);
	}

	@Override
	public BuyHistory getBuyHistoryByUserIdGoodsId(Long userId, Long goodsId, int goodsType) {
		return buyHistoryDao.selectByUserIdGoodsId(userId, goodsId, goodsType);
	}

	@Override
	public PageList<BuyHistoryDto> getBuyHistoryDtoByUserId(Integer pageIndex, Integer pageSize, Long userId) {
		int count = buyHistoryDao.countByParams(userId);
		PageData pageData = new PageData();
		List<BuyHistoryDto> listD = new ArrayList<>();
		PageList<BuyHistoryDto> pageList = new PageList<>();
		if (count > 0) {
			int pageIndexInt = pageIndex == null ? 1 : pageIndex;
			pageData = PageData.createPage(count, pageIndexInt, pageSize);
			List<BuyHistory> list = buyHistoryDao.pageByParams(pageData.getBeginIndex(), pageData.getPageSize(), userId);
			if (!StringUtils.isEmptyList(list)) {
				for (BuyHistory buy : list) {
					if (buy.getGoodsType() == 1) {
						CourseDto courseDto = courseService.getCourseDtoByCourseId(buy.getGoodsId());
						if (courseDto != null) {
							BuyHistoryDto buyDto = new BuyHistoryDto(buy, courseDto);
							listD.add(buyDto);
						}
					}
				}
			}
		}
		pageList = new PageList<>(listD, pageData);
		return pageList;
	}

	@Override
	public List<BuyHistory> getBuyHistoryByGoodsId(int pageIndex, int pageSize, Long goodsId, int goodsType) {
		int beginIndex = (pageIndex - 1) * pageSize;
		return buyHistoryDao.selectByGoodsId(beginIndex, pageSize, goodsId, goodsType);
	}

}
